/**
 * Copyright 2006 Brad Reynolds
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.leeloo.databinding.internal.ui;

import org.eclipse.jface.viewers.ICellModifier;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.widgets.TreeItem;
import org.leeloo.core.Tag;
import org.leeloo.core.TagService;

/**
 * {@link ICellModifier} that allows for the editing of
 * {@link LabeledTagTreeNode LabeledTagTagTreeNodes}.
 * 
 * @author Brad Reynolds
 */
public class LabeledTagTreeNodeCellModifier implements ICellModifier {
    public static final String VALUE_PROPERTY = "value"; //$NON-NLS-1$

    private final TagService tagService;

    private final TreeViewer treeViewer;

    public LabeledTagTreeNodeCellModifier(TreeViewer treeViewer, TagService tagService) {
        if (tagService == null) {
            throw new IllegalArgumentException("Parameter tagService was null."); //$NON-NLS-1$
        }

        this.tagService = tagService;
        this.treeViewer = treeViewer;
    }

    public boolean canModify(Object element, String property) {
        boolean result = false;
        
        if (element instanceof LabeledTagTreeNode && VALUE_PROPERTY.equals(property)) {
            result = ((LabeledTagTreeNode) element).isEditable();
        }
        
        return result;
    }

    public Object getValue(Object element, String property) {
        String result = null;
        if (VALUE_PROPERTY.equals(property) && element instanceof LabeledTagTreeNode) {
            LabeledTagTreeNode node = (LabeledTagTreeNode) element;

            Tag tag = tagService.get(node.getValue(), node.getTag().getName());
            if (tag != null) {
                result = tag.getValue();
            }
        }

        return (result != null) ? result : ""; //$NON-NLS-1$
    }

    public void modify(Object element, String property, Object value) {
        if (element instanceof TreeItem) {
            TreeItem item = (TreeItem) element;
            Object data = item.getData();

            if (VALUE_PROPERTY.equals(property) && data instanceof LabeledTagTreeNode) {
                LabeledTagTreeNode node = (LabeledTagTreeNode) data;

                tagService.put(node.getValue(), new Tag(node.getTag().getName(), (String) value));
                treeViewer.update(node, new String[] { VALUE_PROPERTY });
            }
        }
    }
}